<template>
  <div class="roles-container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" class="user-bread">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="roles" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染一级\二级\三级权限 -->
            <el-row v-for=" (item1,i1) in scope.row.children" :key="item1.id"
              :class="['bdbottom','vcenter',i1 == 0?'bdtop':'']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removRightById(scope.row,item1.id)">{{item1.authName}}{{item1.id}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="['vcenter',i2 ==0 ?'': 'bdtop']">
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removRightById(scope.row,item2.id)">
                      {{item2.authName}}{{item2.id}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable
                      @close="removRightById(scope.row,item3.id)">
                      {{item3.authName}}{{item3.id}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column label="角色id" prop="id"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoles(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="closeAddRoleDialog">
      <!-- 表单区域 -->
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="50%" @close="closeEditRoleDialog">
      <!-- 表单区域 -->
      <el-form :model="editRoleForm" :rules="addRoleFormRules" ref="editRoleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="putRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="closeSetRightDialog">
      <!-- 树形区域 -->
      <el-tree :data="rightsTreeData" :props="treeProps" show-checkbox default-expand-all node-key="id"
        :default-checked-keys="defKeys" ref="treeRef">
      </el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 存放角色列表
      roles: [],
      // 是否显示添加角色的对话框
      addRoleDialogVisible: false,
      // 添加角色用的表单数据
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色用的表单验证规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '长度在 1 到 15 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 是否显示编辑角色的对话框
      editRoleDialogVisible: false,
      // 编辑角色用的表单数据
      editRoleForm: {
        roleId: '',
        roleName: '',
        roleDesc: '',
      },
      // 是否显示分配权限的对话框
      setRightDialogVisible: false,
      // 存放权限树数据
      rightsTreeData: [],
      // 树形控件数据绑定对象
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      // 树形控件默认选中的节点
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: '',
    }
  },
  created() {
    // 获取角色列表的数据
    this.getRoles()
  },
  methods: {
    // 获取角色列表数据
    async getRoles() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status != 200) {
        return this.$message.error('获取角色列表数据错误')
      }
      this.roles = res.data
      console.log(this.roles)
    },
    // 关闭添加角色的对话框时
    closeAddRoleDialog() {
      // 重置表单
      this.$refs.addRoleFormRef.resetFields()
    },
    // 在添加角色的对话框中,点击确定,发送请求,添加新角色
    postRoles() {
      // 表单预验证
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return false
        // 发送请求
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        // 请求失败
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        // 请求成功
        this.$message.success('添加角色成功')
        this.getRoles()
        this.addRoleDialogVisible = false
      })
    },
    // 点击删除按钮,删除角色
    async deleteRoles(id) {
      const delFlag = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (delFlag !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRoles()
    },
    // 点击编辑按钮,编辑角色,根据角色id查询信息
    async editRoles(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      // 请求成功,数据赋值
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    // 点击编辑角色的对话框时
    closeEditRoleDialog() {
      // 重置表单
      this.$refs.editRoleFormRef.resetFields()
    },
    // 在编辑角色的对话框中,点击确定,发送请求,更新角色信息
    async putRoles() {
      // console.log(this.editRoleForm.roleId)
      const { data: res } = await this.$http.put(
        'roles/' + this.editRoleForm.roleId,
        this.editRoleForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色信息失败！')
      }
      this.$message.success('更新角色信息成功！')
      this.editRoleDialogVisible = false
      this.getRoles()
    },
    // 删除角色指定权限
    async removRightById(role, rightId) {
      const delFlag = await this.$confirm(
        '此操作将删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (delFlag !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      this.$message.success('删除权限成功！')
      role.children = res.data
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      // 保存角色id
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      this.rightsTreeData = res.data
      this.getDefKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 关闭分配权限的对话框
    closeSetRightDialog() {
      // 隐藏对话框
      this.setRightDialogVisible = false
      // 重置保存权限id的数组
      this.defKeys = []
    },
    // 获取role角色的最底层权限id值,返回数组形式到arr
    getDefKeys(role, arr) {
      if (role.children) {
        role.children.forEach((element) => {
          // 没有children属性,则为最底层的权限
          if (!element.children) {
            // console.log(element.id)
            this.defKeys.push(element.id)
          } else {
            this.getDefKeys(element, this.defKeys)
          }
        })
      }
    },
    // 在分配权限对话框中,点击确定,更新该角色的权限
    async postRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const ridStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: ridStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功')
      this.getRoles()
      this.setRightDialogVisible = false
    },
  },
}
</script>


<style lang="less" scoped>
// 底部边框
.bdbottom {
  border-bottom: 1px solid #ccc;
}
// 顶部边框
.bdtop {
  border-top: 1px solid #ccc;
}
// 垂直居中
.vcenter {
  display: flex;
  align-items: center;
}
// 标签设置
.el-tag {
  margin: 8px;
}
</style>